package com.xs.ahoi.hcxs.service;

import android.app.Service;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import com.xs.ahoi.hcxs.dao.ConfigDao;
import com.xs.ahoi.hcxs.utils.LogUtil;
import com.xs.ahoi.hcxs.utils.StringUtils;

import java.io.IOException;

/**
 * author: ahoi
 * date: 2018/8/21 13:38
 * description: 播放服务
 */
public class BGMService extends Service {

    private MediaPlayer player;
    private ConfigDao configDao = ConfigDao.getInstance();

    @Override
    public IBinder onBind(Intent intent) {
        return new BGMBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        changeSource(configDao.getBgmName());
        float v = configDao.getBgmV() / 100f;
        player.setVolume(v, v);
//            Ahoi.getAuditFocus();
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    private void changeSource(String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return;
        }
        try {
            player.reset();
            AssetFileDescriptor fd = getAssets().openFd("bgm/" + fileName);
            player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            player.prepare();
            player.setLooping(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 该方法包含关于歌曲的操作
    public class BGMBinder extends Binder {

        public void start() {
            if (player != null) {
                changeV(configDao.getBgmV());
                player.start();
            } else {
                LogUtil.e("播放背景失败，player为空");
            }
        }

        // 暂停
        public void pause() {
            if (player != null) {
                player.pause();
            }
        }

        // 切换音乐
        public void changeS(String fileName) {
            boolean playing = player.isPlaying();
            changeSource(fileName);
            if (playing) {
                start();
            }
        }

        // 改变音量
        public void changeV(int v) {
            player.setVolume(v / 100f, v / 100f);
        }
    }

}
